package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.User;
import cn.huhst.cas.weisiqian.service.UserService;
import cn.huhst.cas.weisiqian.util.JSON;
import cn.huhst.cas.weisiqian.util.Utils;

@WebServlet("/Login.do")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(Login.class);
	private UserService userservice = null;

	public Login() {
		super();
		userservice = new UserService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String userpassword = request.getParameter("userpassword");
		String usercheckcode = request.getParameter("checkcode");
		String checkcode = (String) request.getSession().getAttribute("checkcode");
		logger.debug("用户登录的用户名：" + username + " 密码：" + userpassword + " 验证码：" + usercheckcode);
		logger.info("用户登录的用户名：" + username + " 密码：" + Utils.encry(userpassword) + " 验证码：" + usercheckcode);
		HttpSession session = request.getSession();

		JSON json = new JSON();
		if (checkcode.equals(usercheckcode)) {
			json = User.checkUserNameFormat(username, json);
			json = User.checkUserPasswordFormat(userpassword, json);
			if (json.isEmpty()) {
				userpassword = Utils.encry(userpassword);
				User user = userservice.isExistNameAndPassword(username, userpassword);
				logger.debug("usre:" + user);
				if (user != null) {
					if (user.getUsername().equals(username)) {
						if (user.getUserpassword().equals(userpassword)) {
							json.put("status", "ok");
							session.setAttribute("logined", "logined");
							session.setAttribute("username", username);
							session.setAttribute("changeusername", username);
							session.setAttribute("role", user.getRole());
							logger.info("用户登录成功:" + user);
						} else {
							json.put("userpassword", "用户密码错误");
						}
					} else {
						json.put("username", "用户名错误");
					}
				} else {
					json.put("status", "error");
					json.put("msg", "用户不存在");
				}
			} else {
				json.put("status", "error");
			}
		} else {
			json.put("status", "error");
			json.put("msg", "验证码错误");
		}

		// 使验证码失效
		if(!json.isEmpty()){
			session.setAttribute("checkcode", "");
		}
		
		logger.info("JSON:" + json);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
